package com.lvyq.myplayer.adapter

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.daimajia.slider.library.SliderLayout
import com.daimajia.slider.library.SliderTypes.BaseSliderView
import com.daimajia.slider.library.SliderTypes.TextSliderView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.common.util.DataOperationUtils
import com.lvyq.myplayer.common.util.StartActivityUtils
import com.lvyq.myplayer.model.index.IndexBannerBeans
import com.lvyq.myplayer.model.index.IndexItem
import com.lvyq.myplayer.model.index.IndexSectionTitle
import com.lvyq.myplayer.model.index.IndexPickPlayLstBeans
import com.lvyq.myplayer.model.index.IndexVideoBean
import com.lvyq.myplayer.model.index.IndexVideoBeans
import com.lvyq.myplayer.parcelable.MvPagerBeansData
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.ui.activity.AudioPlayerActivity
import com.lvyq.myplayer.ui.activity.IndexDailyActivity
import com.lvyq.myplayer.ui.activity.SingerMainActivity
import com.lvyq.myplayer.ui.activity.VideoPlayerActivity
import com.lvyq.myplayer.ui.activity.collect.IndexCollectActivity
import com.lvyq.myplayer.ui.activity.ranking.TheChartActivity
import com.lvyq.myplayer.util.GridSpacingItemDecoration
import com.lvyq.myplayer.util.ThreadUtil
import com.lvyq.myplayer.util.URLProviderUtils
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * 文件描述：IndexUnifiedAdapter 首页统一适配器
 * 作者：lvyq
 * 创建时间：2025-03-26
 * 修改时间：2025-03-26
 */
class IndexUnifiedAdapter(
    private val context: Context?,
    private val items: List<IndexItem>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // 定义 viewType 常量
    companion object {
        const val BANNER = 0
        const val GEDAN = 1
        const val HOT_SONG = 2
        const val TITLE = 3
        const val VIDEO = 4
        const val LAST_SONG=5
    }

    // 定义点击事件接口
    interface OnItemClickListener {
        fun onItemClick(data: IndexSectionTitle, position: Int)
    }
    private var onItemClickListener: OnItemClickListener? = null
    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }



    override fun getItemViewType(position: Int): Int {
        return when (items[position]) {
            is IndexItem.Banner -> BANNER
            is IndexItem.GeDan -> GEDAN
            is IndexItem.HotSong -> HOT_SONG
            is IndexItem.SectionTitle -> TITLE
            is IndexItem.Video -> VIDEO
            is IndexItem.LastSong -> LAST_SONG
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup,  viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            BANNER -> BannerViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_index_top, parent, false)
            )
            GEDAN -> GeDanViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_horizontal_list, parent, false)
            )
            HOT_SONG -> HotSongViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_horizontal_grid_list, parent, false)
            )
            TITLE -> TitleViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_section_title, parent, false)
            )
            VIDEO->VideoViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_horizontal_list,parent,false)
            )
            LAST_SONG->LastSongViewHolder(
                LayoutInflater.from(context).inflate(R.layout.item_horizontal_grid_list_5,parent,false)
            )
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }



    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (val item = items[position]) {
            is IndexItem.Banner -> (holder as BannerViewHolder).bind(item.bannerData.rows)
            is IndexItem.GeDan -> (holder as GeDanViewHolder).bind(item.geDanData)
            is IndexItem.HotSong -> (holder as HotSongViewHolder).bind(item.hotSong)
            is IndexItem.SectionTitle -> (holder as TitleViewHolder).bind(item.sectionTitle)
            is IndexItem.Video->( holder as VideoViewHolder).bind(item.video)
            is IndexItem.LastSong ->(holder as LastSongViewHolder).bind(item.lastSong)
        }
    }

    override fun getItemCount() = items.size

    // 定义各个 ViewHolder
   inner class BannerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        BaseSliderView.OnSliderClickListener, View.OnClickListener {

        val sliderLayout: SliderLayout
        val indexTuijian:ImageView
        val indexSinger:ImageView
        val indexGedan:ImageView
        val indexDiantai:ImageView
        val indexPaihang:ImageView
        val indexCollect:ImageView
        init {
            sliderLayout = itemView.findViewById(R.id.slider);
            indexTuijian= itemView.findViewById(R.id.index_tuijian)
            indexSinger= itemView.findViewById(R.id.index_singer)
            indexGedan= itemView.findViewById(R.id.index_gedan)
            indexDiantai= itemView.findViewById(R.id.index_diantai)
            indexPaihang =itemView.findViewById(R.id.index_paihang)
            indexCollect =itemView.findViewById(R.id.index_collect)

            indexTuijian.setOnClickListener(this)
            indexSinger.setOnClickListener(this)
            indexGedan.setOnClickListener(this)
            indexDiantai.setOnClickListener(this)
            indexPaihang.setOnClickListener(this)
            indexCollect.setOnClickListener(this)
        }
        fun bind(data: List<IndexBannerBeans>) {
            val url_maps = HashMap<String, String>()
            for (da in data){
                url_maps.put(da.id.toString(),da.bgImg)
            }
            if (url_maps.size>0){
                for ((key,value ) in url_maps){
                    val textSliderView = TextSliderView(context)
                    textSliderView
                        .description("") //显示文本
                        .image(value)
                        .setScaleType(BaseSliderView.ScaleType.Fit)
                        .setOnSliderClickListener(this)
                    sliderLayout.addSlider<BaseSliderView>(textSliderView)
                }
            }

        }

        /**
         * banner 点击事件
         */
        override fun onSliderClick(slider: BaseSliderView?) {
            ThreadUtil.runOnMainThread({
                Toast.makeText(context, "开发中", Toast.LENGTH_SHORT).show()
            })
        }

        override fun onClick(v: View?) {
            when(v?.id){
                R.id.index_tuijian->{
                    var intent = Intent(context, IndexDailyActivity::class.java)
                    //跳转每日推荐
                    context?.let {
                        it.startActivity(intent)
                    }
                }
                R.id.index_singer->{
                    ThreadUtil.runOnMainThread{
                        var intent=Intent(context, SingerMainActivity::class.java)
                        context?.let {
                            it.startActivity(intent)
                        }
                    }
                }
                R.id.index_paihang->{
                    ThreadUtil.runOnMainThread{
                        var intent=Intent(context, TheChartActivity::class.java)
                        context?.let {
                            it.startActivity(intent)
                        }
                    }
                }
                //我的收藏
                R.id.index_collect->{
                    ThreadUtil.runOnMainThread{
                        var intent = Intent(context, IndexCollectActivity::class.java)
                        //跳转每日推荐
                        context?.let {
                            it.startActivity(intent)
                        }
                    }
                }
                R.id.index_diantai->{
                    ThreadUtil.runOnMainThread{
                        Toast.makeText(context, "开发中", Toast.LENGTH_SHORT).show()
                    }
                }

                }
            }

    }

    /**
     * 推荐歌单
     */
  inner class GeDanViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val recyclerView: RecyclerView = itemView.findViewById(R.id.rv_horizontal)
        fun bind(data: List<IndexPickPlayLstBeans>) {
            recyclerView.layoutManager = LinearLayoutManager(
                itemView.context,
                LinearLayoutManager.HORIZONTAL,
                false
            ).apply {
                initialPrefetchItemCount = 4
            }
            val  indexGeDanAdapter=IndexGeDanAdapter(context,data)
            recyclerView.adapter = indexGeDanAdapter
            recyclerView.setHasFixedSize(true)

            indexGeDanAdapter.setOnItemClickListener(object :IndexGeDanAdapter.OnItemClickListener{
                override fun onItemClick(data: IndexPickPlayLstBeans, position: Int) {
                    // 处理点击事件，
                    ThreadUtil.runOnMainThread({
                        Toast.makeText(context, "开发中", Toast.LENGTH_SHORT).show()
                    })

                }

            })
        }
    }

    /**
     * 热门单曲
     */
   inner class HotSongViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val recyclerView: RecyclerView = itemView.findViewById(R.id.rv_horizontal_grid)
        fun bind(list: ArrayList<SongInfoData>) {
            recyclerView.layoutManager == GridLayoutManager(context, 3).apply {
                orientation = RecyclerView.HORIZONTAL
                spanSizeLookup = CustomSpanSizeLookup(3)
            }
            val itemDecoration = GridSpacingItemDecoration(
                spanCount = 3,      // 与你的 spanCount 一致
                spacing = 16,       // 间距大小（单位：像素）
                includeEdge = false    // 是否包含边缘间距
            )
            recyclerView.addItemDecoration(itemDecoration)

            val  indexHotSongAdapter=IndexHotSongAdapter(context,list)
            recyclerView.adapter = indexHotSongAdapter
            recyclerView.setHasFixedSize(true) //设置RecyclerView的尺寸固定

            indexHotSongAdapter.setOnItemClickListener(object :IndexHotSongAdapter.OnItemClickListener{
                override fun onItemClick(data: SongInfoData, position: Int) {
                    startAudioPlayActivity(data,position,list)
                }

            })
        }


    }
    /**
     * 自定义 SpanSizeLookup
     */
    inner class CustomSpanSizeLookup( val spanCount: Int) : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            // 每行固定3列，所以每个 item 占1个 span
            return 1
        }
    }
    /**
     * 分割
     */
    inner class TitleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val section_title:TextView
        val tv_more:TextView
        init {
            section_title=itemView.findViewById(R.id.section_title)
            tv_more=itemView.findViewById<TextView>(R.id.tv_more)
        }
        fun bind(data: IndexSectionTitle) {
            section_title.text=data.title

            // 设置 tv_more 点击事件
            tv_more.setOnClickListener {
                onItemClickListener?.onItemClick(data,position) // 触发更多点击回调
            }
        }

    }

    /**
     * 推荐MV  -直接使用视图，不重新创建view -PS:对比GeDanViewHolder使用recyclerView 的方式
     */
    inner class VideoViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        //private val recyclerView: RecyclerView = itemView.findViewById(R.id.rv_horizontal)
        fun bind(video: IndexVideoBean) {
            (itemView as RecyclerView) .layoutManager=LinearLayoutManager(
                context,LinearLayoutManager.HORIZONTAL,false
            ).apply {  }

            val indexVideoAdapter = IndexVideoAdapter(context)
            (itemView as RecyclerView).adapter= indexVideoAdapter
            indexVideoAdapter.setData(video)
            (itemView as RecyclerView).setHasFixedSize(false)

            indexVideoAdapter.setOnItemClickListener(object : IndexVideoAdapter.OnItemClickListener {
                override fun onItemClick(video: IndexVideoBeans, position: Int) {
                    val client = OkHttpClient()
                    val request = Request.Builder()
                        .url(URLProviderUtils.reUpdVideo(video.id))
                        .build()

                    // 改为异步请求
                    client.newCall(request).enqueue(object : Callback {
                        override fun onResponse(call: Call, response: Response) {
                            val newVideoUrl = response.body?.string()
                            // 在主线程更新UI
                            Handler(Looper.getMainLooper()).post {
                                // 点击跳转播放页面
                                var intent = Intent(context, VideoPlayerActivity::class.java)
                                val data = MvPagerBeansData(video.id,"TJ",video.title,video.singer,newVideoUrl,video.img,video.singer,"")
                                intent.putExtra("data",data)
                                context?.let {
                                    it.startActivity(intent)
                                }
                            }
                        }

                        override fun onFailure(call: Call, e: IOException) {
                            // 错误处理
                            Log.e("MediaPlayerService", "Request failed: ${e.message}")
                            /* nextMusicPlay()*/
                        }
                    })

                    // 跳转到详情页示例
                    /*val intent = Intent(context, VideoPlayerActivity::class.java)
                    //intent.putExtra("videoData", data)
                    context?.let {
                        it.startActivity(intent)
                    }*/
                }
            })
        }

    }



    /**
     *最新单曲 三行
     */
    inner class LastSongViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val recyclerView: RecyclerView = itemView.findViewById(R.id.rv_horizontal_grid)
        fun bind(lastSong: ArrayList<SongInfoData>) {
            recyclerView.layoutManager==GridLayoutManager(context,5).apply {
                orientation = RecyclerView.HORIZONTAL
                spanSizeLookup = CustomSpanSizeLookup(5)
            }
            val itemDecoration = GridSpacingItemDecoration(
                spanCount = 5,      // 与你的 spanCount 一致
                spacing = 16,       // 间距大小（单位：像素）
                includeEdge = false    // 是否包含边缘间距
            )
            recyclerView.addItemDecoration(itemDecoration)
            val  indexLastSongAdapter=IndexLastSongAdapter(context,lastSong)
            recyclerView.adapter = indexLastSongAdapter
            //设置RecyclerView的尺寸
            recyclerView.setHasFixedSize(true)

            indexLastSongAdapter.setOnItemClickListener(object :IndexLastSongAdapter.OnItemClickListener{
                override fun onItemClick(data: SongInfoData, position: Int) {

                    startAudioPlayActivity(data,position,lastSong)

                }
            })
        }

    }


    /**
     * 跳转到歌曲播放界面
     */
    fun  startAudioPlayActivity(data: SongInfoData, position: Int,lastSong: ArrayList<SongInfoData>){
        ThreadUtil.runOnMainThread({
            // 点击跳转播放页面
            var intent = Intent(context, AudioPlayerActivity::class.java)
            intent.putExtra("position",position)
            //跳转播放页
            context?.let {
                DataOperationUtils.installCurrentPlayLst(it,lastSong)
                it.startActivity(intent)
            }
        })
    }
}

